package com.xc.file.web.rest;

import com.xc.core.annotation.Authority;
import com.xc.core.dto.UploadDto;
import com.xc.core.enums.RedisPrefix;
import com.xc.core.model.TokenModel;
import com.xc.core.utils.RedisUtils;
import com.xc.file.bean.TokenUploadBean;
import com.xc.file.config.Constants;
import com.xc.file.enums.FailCode;
import com.xc.file.enums.UploadType;
import com.xc.file.model.UploadModel;
import com.xc.file.service.UploadService;
import com.xc.tool.utils.JSONUtils;
import com.xc.tool.utils.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * <p>上传文件rest接口</p>
 *
 * @author xc
 * @version v1.0.0
 */
@RestController
@Api(tags = "上传文件rest接口")
public class UploadRest {

    @Autowired
    private UploadService uploadService;
    @Autowired
    private Constants constants;

    @ApiOperation(value = "token上传文件",
            notes = "1，单次上传，传入的size和文件的size必须相等\n" +
                    "2，分段上传，首次请求fileIndex必须等于零，根据返回的renewalSize确定每次上传多少\n")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户token", name = "token", paramType = "header", required = true),
            @ApiImplicitParam(value = "文件数据", name = "file", paramType = "body", required = true),
    })
    @PostMapping("/upload_file")
    @Authority
    public UploadDto uploadFile(TokenModel tokenModel, TokenUploadBean tokenUploadBean, MultipartFile file) {
        if (file == null) {
            throw FailCode.FILE_NOT_EMPTY.getOperateException();
        }
        long time = tokenModel.getUpdateTime().getTime() + (tokenModel.getValidTime() / 2);
        if (time < new Date().getTime()) {
            tokenModel.setUpdateTime(new Date());
            RedisUtils.set(RedisPrefix.ACCESS.getKey() + tokenModel.getAccessToken(), JSONUtils.getStringByObject(tokenModel));
        }
        // 封装数据上传文件
        UploadModel uploadModel = ObjectUtils.convert(new UploadModel(), tokenUploadBean);
        uploadModel.setUserId(tokenModel.getUserId());
        uploadModel.setUserIds(tokenModel.getUserIds());
        uploadModel.setFile(file);
        uploadModel.setUploadType(UploadType.TOKEN);
        UploadDto uploadDto = uploadService.uploadFile(uploadModel);
        if (uploadDto.getUploadUrl() != null) {
            uploadDto.setUploadUrl(uploadDto.getUploadUrl() + "/upload_file");
        } else {
            uploadDto.setUploadUrl(constants.getLocalUrl() + "/upload_file");
        }
        return uploadDto;
    }
}
